package com.weichai.app.page.home.view;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.weichai.app.R;
import com.weichai.app.arch.base.BaseFragment;
import com.weichai.app.arch.config.RouterParams;
import com.weichai.app.arch.utils.StringUtil;
import com.weichai.app.bean.InformationEntity;
import com.weichai.app.bean.SearchEntranceEntity;
import com.weichai.app.bean.SearchInfoEntity;
import com.weichai.app.databinding.FragmentSearchBinding;
import com.weichai.app.page.home.adapter.SearchAdapter;
import com.weichai.app.page.home.adapter.SearchItemDecoration;
import com.weichai.app.page.home.viewmodel.SearchVM;
import com.weichai.app.views.flowlayout.FlowLayout;
import com.weichai.app.views.flowlayout.TagAdapter;
import com.weichai.app.views.flowlayout.TagFlowLayout;

import java.util.List;

import dev.utils.app.KeyBoardUtils;
import dev.utils.app.SizeUtils;

/**
 * 首页-搜索界面
 *
 * @author ccs
 * @date 2021年11月17日09点48分
 */
public class SearchFragment extends BaseFragment<FragmentSearchBinding, SearchVM> {

    @Override
    protected void initView() {
        mViewModel.queryByHot();
        mViewBinding.tagSearchHistory.setAdapter(new TagAdapter<String>(mViewModel.tagHistoryLiveData.getValue()) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.item_search, parent, false);
                tv.setText(s);
                return tv;
            }
        });

        mViewModel.tagHistoryLiveData.observe(this, new Observer<List<String>>() {
            @Override
            public void onChanged(List<String> list) {
                mViewBinding.tagSearchHistory.setAdapter(new TagAdapter<String>(list) {
                    @Override
                    public View getView(FlowLayout parent, int position, String s) {
                        TextView tv = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.item_search, parent, false);
                        tv.setText(s);
                        return tv;
                    }
                });
            }
        });

        mViewBinding.tagSearchHistory.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                String s = mViewModel.tagHistoryLiveData.getValue().get(position);
                mViewBinding.etContent.setText(s);
                mViewBinding.etContent.setSelection(s.length());
                mViewModel.search();
                return true;
            }
        });

        mViewModel.tagHotLiveData.observe(mActivity, list -> mViewBinding.tagHotSearch.setAdapter(new TagAdapter<String>(mViewModel.tagHotLiveData.getValue()) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.item_search, parent, false);
                tv.setText(s);
                return tv;
            }
        }));

        mViewBinding.tagHotSearch.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                String s = mViewModel.tagHotLiveData.getValue().get(position);
                mViewBinding.etContent.setText(s);
                mViewBinding.etContent.setSelection(s.length());
                mViewModel.search();
                return true;
            }
        });

        mViewBinding.etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    mViewModel.isShowClear.setValue(false);
                    if (null != mViewModel.searchEntityList.getValue() && !mViewModel.searchEntityList.getValue().isEmpty()) {
                        mViewModel.isShowTag.setValue(false);
                    } else {
                        mViewModel.isShowTag.setValue(true);
                    }
                } else {
                    mViewModel.isShowClear.setValue(true);
                    mViewModel.isShowTag.setValue(false);
                }
                mViewModel.searchContent.setValue(s.toString());
            }
        });

        if (null != getArguments()) {
            mViewBinding.etContent.setText(getArguments().getString("searchContent"));
            mViewModel.search();
        }

        mViewBinding.ivClear.setOnClickListener(v -> {
            mViewBinding.etContent.setText("");
        });

        SearchAdapter searchAdapter = new SearchAdapter();
        mViewBinding.rv.setLayoutManager(new LinearLayoutManager(getActivity()));
        mViewBinding.rv.addItemDecoration(new SearchItemDecoration(0, SizeUtils.dipConvertPx(16),
                0, SizeUtils.dipConvertPx(16)));
        mViewBinding.rv.setAdapter(searchAdapter);
        mViewModel.isShowEmptyView.observe(mActivity, isShowEmptyView -> {
            searchAdapter.setUseEmpty(isShowEmptyView);
            searchAdapter.setEmptyView(R.layout.search_empty_view);
        });

        searchAdapter.setOnInfoItemClickListener(new SearchAdapter.OnInfoItemClickListener() {
            @Override
            public void onInfoItemClick(SearchInfoEntity searchInfoEntity) {
                InformationEntity.ListBean listBean = new InformationEntity.ListBean();
                listBean.newsCode = searchInfoEntity.newsCode;
                listBean.likes = searchInfoEntity.likes;
                listBean.like = searchInfoEntity.like;
                Bundle bundle = new Bundle();
                bundle.putParcelable("listBean", listBean);
                navigate(new RouterParams(R.id.infoDetailsFragment, bundle));
            }
        });

        searchAdapter.setOnEntranceItemClickListener(new SearchAdapter.OnEntranceItemClickListener() {
            @Override
            public void onEntranceItemClick(SearchEntranceEntity searchEntranceEntity) {
                switch (searchEntranceEntity.functionName) {
                    case "更多":
                        if (StringUtil.isLogin()) {
                            navigate(new RouterParams(R.id.editApplicationFragment));
                        }
                        break;
                    case "客服电话":
                        StringUtil.callPhone("123456789");
                        break;
                    case "故障码查询":
                        if (StringUtil.isLogin()) {
                            navigate(new RouterParams(R.id.faultCodeFragment));
                        }
                        break;
                    case "服务站":
                        if (StringUtil.isLogin()) {
                            navigate(new RouterParams(R.id.serviceStationFragment));
                        }
                        break;
                    default:
                        break;
                }
            }
        });

        mViewBinding.etContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    mViewModel.search();
                    return true;
                }
                return false;
            }
        });

        mViewBinding.etContent.requestFocus();
        KeyBoardUtils.openKeyboardDelay();
    }

    @Override
    protected void initData() {

    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_search;
    }
}
